`
if Conditions
In bash, we can use an if condition to execute some code only when a
condition is met. Its syntax is as follows:
if [[ condition ]]; then
# do something if the condition is met
else
# do something if the condition is not met
fi
We start with the if keyword, followed by a test conditions between double
brackets ([[ ]]). We then use the ; character to separate the if keyword from
the then keyword, which allows us to introduce a block of code that runs only if
the condition is true.
Next, we use the else keyword to introduce a fallback code block that runs if
the condition is not met. Note that else is optional, and you may not always need
it. Finally, we close the if condition with the fi keyword (which is if inversed).
N O T E
In some operating systems, such as those often used in containers, the default shell
might not necessarily be bash. To account for these cases, you may want to use single
brackets ([…]) rather than double brackets to enclose your condition. This use of
single brackets meets the POSIX standard and should work on almost any Unix
derivative, including Linux.
Let’s see an if condition in practice. Listing 2-1 uses an if condition to test
whether a file exists, and if not, creates it.
#!/bin/bash
FILENAME="flow_control_with_if.txt"
if [[ -f "${FILENAME}" ]]; then
echo "${FILENAME} already exists."
exit 1
else
touch "${FILENAME}"
fi
Listing 2-1
An if condition to test for the existence of a file
We first create a variable named FILENAME containing the name of the file
we need. This saves us from having to repeat the filename in the code. We then
introduce the if statement, which uses a condition that tests for the existence of
files with the -f file test operator. If this condition is true, we use echo to print to
the screen a message explaining that the file already exists and then exit the
program using the status code 1 (failure). Using the else block, which will
execute only if the file does not exist, we create the file using the touch
command.
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks